package com.showworkflow.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;

@Service
public class PythonExecutorService {

    @Value("${python.executable}")
    private String pythonExecutable;

    @Value("${python.script.path}")
    private String scriptPath;

    public String convertHtmlToWord(String htmlContent, String outputPath) throws IOException {
        // 验证HTML内容是否包含基本HTML标签
        if (!htmlContent.contains("<html") && !htmlContent.contains("<body") && !htmlContent.contains("<div")) {
            throw new IOException("无效的HTML内容，缺少必要的HTML标签");
        }

        File tempHtml = File.createTempFile("temp", ".html");
        try {
            java.nio.file.Files.write(tempHtml.toPath(), htmlContent.getBytes(java.nio.charset.StandardCharsets.UTF_8));

            ProcessBuilder pb = new ProcessBuilder(
                    pythonExecutable,
                    Paths.get(scriptPath).toString(),
                    tempHtml.getAbsolutePath(),
                    outputPath
            );
            pb.environment().put("PYTHONIOENCODING", "utf-8");

            pb.redirectErrorStream(true);
            Process process = pb.start();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"));
                 BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), "UTF-8"))) {
                
                StringBuilder output = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                    if (line.startsWith("转换成功！Word文档已保存至: ")) {
                        return line.substring("转换成功！Word文档已保存至: ".length());
                    }
                }

                StringBuilder errorOutput = new StringBuilder();
                while ((line = errorReader.readLine()) != null) {
                    errorOutput.append(line).append("\n");
                }

                if (errorOutput.length() > 0) {
                    throw new IOException("Python脚本执行错误: " + errorOutput.toString());
                }
                throw new IOException("Python脚本执行失败，未返回预期结果。输出: " + output.toString());
            }
        } finally {
            tempHtml.delete();
        }
    }
}